﻿using System;
using System.Collections.Generic;
using System.Linq;
using CourseManager.Model.Exception;

namespace CourseManager.Model.Data
{
	public class TeacherDAO
	{

		public static void Add(string id, string name, string dept, string sex, string password)
		{
			UserDAO.Add(id, password, RoleType.TEACHER);
			DBEntity ent = new DBEntity();
			ent.AddToTab_Teacher(new Tab_Teacher
			                     	{
			                     		teacherId = id,
										name = name,
										dept = dept,
										sex = sex
			                     	});
			ent.SaveChanges();
		}

		public static void Remove(string id)
		{
			UserDAO.Remove(id);
			DBEntity ent = new DBEntity();
			Tab_Teacher teacher = (from _teacher in ent.Tab_Teacher
								   where _teacher.teacherId.Equals(id)
								   select _teacher).FirstOrDefault();
			if(teacher != null)
			{
				ent.DeleteObject(teacher);
				ent.SaveChanges();
			}
		}

		public static Tab_Teacher FindById(string id)
		{
			DBEntity ent = new DBEntity();
			Tab_Teacher teacher = (from _teacher in ent.Tab_Teacher
			                       where _teacher.teacherId.Equals(id)
			                       select _teacher).FirstOrDefault();
			if(teacher == null)
			{
				throw new CMException("Can not find teacher{id = " + id + "} from database");
			}
			return teacher;
		}

		public static IEnumerable<Tab_Teacher> FindAll()
		{
			return from _teacher in new DBEntity().Tab_Teacher select _teacher;
		}

		public static IEnumerable<Tab_Teacher> FindByKeyword()
		{
			return from _teacher in new DBEntity().Tab_Teacher select _teacher;
		}

		public static IEnumerable<Tab_Course> GetCourseList(string teacherId)
		{
			return from course in new DBEntity().Tab_Course
			       where course.teacherId.Equals(teacherId)
			       select course;
		}
	}
}